/*Author: Rony Lahav (ID:043489889)*/

import java.util.Collection;
import java.util.TreeMap;


/**
 * Manages the AV message sending at each frequency seconds to all online peer
 * Except for first load of peer when it send AV message to all peers in the list
 */
public class AVManager implements Runnable{
	protected boolean atLoadStatus=true;
	public void run() {
		TreeMap<String,DBTuple> peersForAV;
		do {
			if (atLoadStatus){	//at first load of peer send to all peers in list
				// Get from the DB all of the tuples to which I should send AV to
				peersForAV = (TreeMap<String,DBTuple>)DataBase.getInstance().getAllTuples();
				atLoadStatus=false;
			}
			else{
				// Get from the DB all of the online tuples to which I should send AV to
				peersForAV = (TreeMap<String,DBTuple>)DataBase.getInstance().getAllOnlineRegTuples();
			}
			//run over all peers and send an AV message
			Collection<DBTuple> c = peersForAV.values();
			String AVmsg="";
			if (c.size()>0){	//at least 1 tuple is online
				AVmsg=createAVMessage();
			}
			for (DBTuple tuple : c) {
				if (final_project.isShutDown()) {
					break;
				}
				// Open a dedicated thread to send AV to one specific peer
				sendAVToOneTuple(tuple, AVmsg);
			}
			
			try{
				if (!final_project.isShutDown()) {
					// Sleep until next AV frequency
					Thread.sleep(final_project.frequency);
				}
			}
			catch (InterruptedException e){}
		} while (!final_project.isShutDown());
	}

	/**
	 * create AV message in correct format
	 * @return AV message
	 */
	protected String createAVMessage() {
		String message = MessageCenter.getInstance().createMessage_AV();
		return message;
	}
	
	protected void sendAVToOneTuple(DBTuple tuple, String AVmsg){
		// Open a dedicated thread to send AV to one specific peer
		SingleUDPMessageSender singleAV = new SingleUDPMessageSender(final_project.mainUDPSoc, tuple, AVmsg, final_project.getNewUniqueID());
		Thread thread = new Thread(singleAV);
		final_project.addThreadToLivingList(singleAV.getUniqueID(), thread);
		thread.start();
	}
}
